package org.linlinjava.litemall.wx.service;

import static org.linlinjava.litemall.wx.util.WxResponseCode.COMMON_DETAIL_IS_NULL;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.linlinjava.litemall.core.util.ConvertUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.constant.DBConmonConstant;
import org.linlinjava.litemall.db.service.PurchaseService;
import org.linlinjava.litemall.wx.util.WxPurchaseStatusUtil;
import org.linlinjava.litemall.wx.vo.PurchaseStatisticsVo;
import org.linlinjava.litemall.wx.vo.QualificationsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.hutool.core.map.MapUtil;

@Service
public class WxPurchaseService {
	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private WxQualificationsService wxQualificationsService;

	/**
	 * 我的采购统计信息
	 * 
	 * @param userId
	 * @return
	 */
	public Map<Object, Object> purchaseStatistics(Integer userId) {
		List<String> querys = Lists.newArrayList();
		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo != null) {
			// TODO
			switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
			case Personal:
				// 个人登录情况下，默认只能看到厂家的采购信息
				querys.add(" fp.user_type = 1 ");
				break;
			case Manufactor:
				// 厂家登录情况下，默认只能看到供应商供的采购信息
				querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
				break;
			case Distributor:
				// 供应商登录情况下，默认只能看到自己的采购信息
				querys.add(" fp.user_id = " + userId + " ");
				break;
			default:
				break;
			}
		}
		querys.add(" u.id = " + userId + " ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,fp.publish_dt desc ";

		List<Map> mapList = purchaseService.getPurchases(query, orderByClause);

		int waitQute = 0;
		int quoted = 0;
		int winningBid = 0;
		int notBid = 0;
		int waitCheck = 0;
		int checkOk = 0;
		int checkFail = 0;
		if (CollectionUtils.isNotEmpty(mapList)) {
			PurchaseStatisticsVo vo = null;
			mapList = ConvertUtils.sourceToCamelCaseMap(mapList);
			for (Map map : mapList) {
				vo = ConvertUtils.mapToObject(map, PurchaseStatisticsVo.class);
				if (WxPurchaseStatusUtil.isWaitQuteStatus(vo) && !vo.isUhaDelete()) {
					waitQute++;
				}
				if (WxPurchaseStatusUtil.isQuotedStatus(vo)) {
					quoted++;
				}
				if (WxPurchaseStatusUtil.isWinningBidStatus(vo)) {
					winningBid++;
				}
				if (WxPurchaseStatusUtil.isNotBidStatus(vo)) {
					notBid++;
				}
				if (WxPurchaseStatusUtil.isWaitCheckStatus(vo)) {
					waitCheck++;
				}
				if (WxPurchaseStatusUtil.isCheckOkStatus(vo)) {
					checkOk++;
				}
				if (WxPurchaseStatusUtil.isCheckFailStatus(vo)) {
					checkFail++;
				}
			}
		}

		Map<Object, Object> result = new HashMap<Object, Object>();
		result.put("waitQute", waitQute);
		result.put("quoted", quoted);
		result.put("winningBid", winningBid);
		result.put("notBid", notBid);
		result.put("waitCheck", waitCheck);
		result.put("checkOk", checkOk);
		result.put("checkFail", checkFail);
		return result;
	}

	public Object herbTotalList(Integer userId, Byte type, Integer page, Integer limit, String sort, String order,
			Integer herbId, String searchValue) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo == null) {
			return ResponseUtil.fail(COMMON_DETAIL_IS_NULL, "未获取到资质信息，请刷新重试");
		}

		List<String> querys = Lists.newArrayList();
		// TODO
		switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
		case Personal:
			// 个人登录情况下，默认只能看到厂家的采购信息
			querys.add(" fp.user_type = 1 ");
			break;
		case Manufactor:
			// 厂家登录情况下，默认只能看到供应商供的采购信息
			querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
			break;
		case Distributor:
			// 供应商登录情况下，默认只能看到自己的采购信息
			querys.add(" fp.user_id = " + userId + " ");
			break;
		default:
			break;
		}

		/*if (herbId != null) {
			querys.add(" fpi.herb_id = " + herbId + " ");
		}*/

		if (!StringUtils.isEmpty(searchValue)) {
			querys.add(
					" CONCAT(IFNULL(s.company_name,''),IFNULL(h.herb_name,''),IFNULL(h.code,''),IFNULL(fp.contact_name,''),IFNULL(fp.contact_tel,'')) LIKE '%"
							+ searchValue + "%' ");
		}
		querys.add(" u.id = " + userId + " ");
		querys.add(" fp.status = 2 ");
		querys.add(" (fpi.status = 0 or fpi.status = 1) ");
		querys.add(" qp.status is null ");
		querys.add(" uha.deleted = 0 ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		querys.add(" fpi.check_status = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,publish_dt desc ";

		PageHelper.startPage(page, limit);
		List<Map> mapList = purchaseService.getHerpTotalPurchases(query, orderByClause);
		Page<Map> list = (Page) mapList;

		Map<String, Object> data = Maps.newHashMap();
		data.put("list", ConvertUtils.sourceToCamelCaseMap(list));
		data.put("total", list.getTotal());
		data.put("page", list.getPageNum());
		data.put("limit", list.getPageSize());
		data.put("pages", list.getPages());
		return ResponseUtil.ok(data);
	}

	public Object list(Integer userId, Byte type, Integer page, Integer limit, String sort, String order,
			String genericName, String describe, String searchValue) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo == null) {
			return ResponseUtil.fail(COMMON_DETAIL_IS_NULL, "未获取到资质信息，请刷新重试");
		}

		List<String> querys = Lists.newArrayList();
		// TODO
		/*switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
		case Personal:
			// 个人登录情况下，默认只能看到厂家的采购信息
			querys.add(" fp.user_type = 1 ");
			break;
		case Manufactor:
			// 厂家登录情况下，默认只能看到供应商供的采购信息
			querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
			break;
		case Distributor:
			// 供应商登录情况下，默认只能看到自己的采购信息
			querys.add(" fp.user_id = " + userId + " ");
			break;
		default:
			break;
		}*/
		// 状态切换 TODO
		switch (type) {
		case 1:// 待报价
			//querys.add(" uha.deleted = 0 ");
			querys.add(" fp.status = 2 ");
			querys.add(" (fpi.status = 0 or fpi.status = 1) ");
			querys.add(" fpi.check_status = 0 ");
			querys.add(" qp.status is null ");
			break;
		case 2:// 已报价
			querys.add(" fp.status = 2 ");
			querys.add(" (fpi.status = 0 or fpi.status = 1) ");
			querys.add(" fpi.check_status = 0 ");
			querys.add(" qp.status = 0 ");
			break;
		case 3:// 已中标
			querys.add(" fp.status = 2 ");
			querys.add(" (fpi.status = 2 or fpi.status = 3) ");
			// 现在中标的药材，送检中也让在中标里显示
			querys.add(" (fpi.check_status = 0 or fpi.check_status = 1) ");
			querys.add(" qp.status = 1 ");
			break;
		case 4:// 未中标
			querys.add(" fp.status = 2 ");
			querys.add(" (fpi.status = 2 or fpi.status = 3) ");
//			querys.add(" fpi.check_status = 0 ");
			querys.add(" qp.status = 0 ");
			break;
		}
//		if (!StringUtils.isEmpty(genericName)) {
//			querys.add(" h.generic_name = '" + StringUtils.trimWhitespace(genericName) + "' ");
//		}
//
//		if (!StringUtils.isEmpty(describe)) {
//			querys.add(" h.describe = '" + StringUtils.trimWhitespace(describe.trim()) + "' ");
//		}

		if (!StringUtils.isEmpty(searchValue)) {
			querys.add(
					" CONCAT(IFNULL(s.company_name,''),IFNULL(h.herb_name,''),IFNULL(h.code,''),IFNULL(fp.contact_name,''),IFNULL(fp.contact_tel,'')) LIKE '%"
							+ searchValue + "%' ");
		}
		//querys.add(" u.id = " + userId + " ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,fp.publish_dt desc ";

		PageHelper.startPage(page, limit);
		List<Map> mapList = purchaseService.getPurchases(query, orderByClause);
		Page<Map> list = (Page) mapList;

		Map<String, Object> data = Maps.newHashMap();
		data.put("list", ConvertUtils.sourceToCamelCaseMap(list));
		data.put("total", list.getTotal());
		data.put("page", list.getPageNum());
		data.put("limit", list.getPageSize());
		data.put("pages", list.getPages());
		return ResponseUtil.ok(data);
	}

	public Object extraList(Integer userId, Byte type, Integer page, Integer limit, String sort, String order,
			String genericName, String describe, String searchValue) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo == null) {
			return ResponseUtil.fail(COMMON_DETAIL_IS_NULL, "未获取到资质信息，请刷新重试");
		}

		List<String> querys = Lists.newArrayList();
		// TODO
		switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
		case Personal:
			// 个人登录情况下，默认只能看到厂家的采购信息
			querys.add(" fp.user_type = 1 ");
			break;
		case Manufactor:
			// 厂家登录情况下，默认只能看到供应商供的采购信息
			querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
			break;
		case Distributor:
			// 供应商登录情况下，默认只能看到自己的采购信息
			querys.add(" fp.user_id = " + userId + " ");
			break;
		default:
			break;
		}
		
		// 待报价
		querys.add(" fp.status = 2 ");
		querys.add(" (fpi.status = 0 or fpi.status = 1) ");
		querys.add(" fpi.check_status = 0 ");
		querys.add(" qp.status is null ");

		if (!StringUtils.isEmpty(genericName)) {
			querys.add(" h.generic_name = '" + genericName + "' ");
		}

		if (!StringUtils.isEmpty(describe)) {
			querys.add(" h.describe = '" + describe + "' ");
		}

		if (!StringUtils.isEmpty(searchValue)) {
			querys.add(
					" CONCAT(IFNULL(s.company_name,''),IFNULL(h.herb_name,''),IFNULL(h.code,''),IFNULL(fp.contact_name,''),IFNULL(fp.contact_tel,'')) LIKE '%"
							+ searchValue + "%' ");
		}
//		querys.add(" u.id = " + userId + " ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,fp.publish_dt desc ";

		PageHelper.startPage(page, limit);
		List<Map> mapList = purchaseService.getExtraPurchases(query,userId, orderByClause);
		Page<Map> list = (Page) mapList;

		Map<String, Object> data = Maps.newHashMap();
		data.put("list", ConvertUtils.sourceToCamelCaseMap(list));
		data.put("total", list.getTotal());
		data.put("page", list.getPageNum());
		data.put("limit", list.getPageSize());
		data.put("pages", list.getPages());
		return ResponseUtil.ok(data);
	}
	
	public List<Map> queryList(Integer userId, int offset, int limit, String searchValue) {
		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo == null) {
			return Lists.newArrayList();
		}

		List<String> querys = Lists.newArrayList();
		// TODO
		switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
		case Personal:
			// 个人登录情况下，默认只能看到厂家的采购信息
			querys.add(" fp.user_type = 1 ");
			break;
		case Manufactor:
			// 厂家登录情况下，默认只能看到供应商供的采购信息
			querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
			break;
		case Distributor:
			// 供应商登录情况下，默认只能看到自己的采购信息
			querys.add(" fp.user_id = " + userId + " ");
			break;
		default:
			break;
		}
		if (!StringUtils.isEmpty(searchValue)) {
			querys.add(
					" CONCAT(IFNULL(s.company_name,''),IFNULL(h.herb_name,''),IFNULL(h.code,''),IFNULL(fp.contact_name,''),IFNULL(fp.contact_tel,'')) LIKE '%"
							+ searchValue + "%' ");
		}
		querys.add(" u.id = " + userId + " ");// TODO 待报价状态
		querys.add(" fp.status = 2 ");
		querys.add(" (fpi.status = 0 or fpi.status = 1) ");
		querys.add(" qp.status is null ");
		//querys.add(" uha.deleted = 0 ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		querys.add(" fpi.check_status = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,fp.publish_dt desc ";

		PageHelper.startPage(offset, limit);
		List<Map> mapList = purchaseService.getPurchases(query, orderByClause);
		if (CollectionUtils.isNotEmpty(mapList)) {
			return ConvertUtils.sourceToCamelCaseMap(mapList);
		}
		return Lists.newArrayList();
	}

	/**
	 * 权限外品类数据
	 * @param userId
	 * @param offset
	 * @param limit
	 * @param searchValue
	 * @return
	 */
	public List<Map> extraQueryList(Integer userId, int offset, int limit, String searchValue) {
		QualificationsVo qualificationsVo = wxQualificationsService.getQualificationsVo(userId);
		if (qualificationsVo == null) {
			return Lists.newArrayList();
		}

		List<String> querys = Lists.newArrayList();
		// TODO
		switch (DBConmonConstant.UserType.getEnumByValue(qualificationsVo.getUserType())) {
		case Personal:
			// 个人登录情况下，默认只能看到厂家的采购信息
			querys.add(" fp.user_type = 1 ");
			break;
		case Manufactor:
			// 厂家登录情况下，默认只能看到供应商供的采购信息
			querys.add(" (fp.user_type = 0 or fp.user_id = " + userId + ") ");
			break;
		case Distributor:
			// 供应商登录情况下，默认只能看到自己的采购信息
			querys.add(" fp.user_id = " + userId + " ");
			break;
		default:
			break;
		}
		if (!StringUtils.isEmpty(searchValue)) {
			querys.add(
					" CONCAT(IFNULL(s.company_name,''),IFNULL(h.herb_name,''),IFNULL(h.code,''),IFNULL(fp.contact_name,''),IFNULL(fp.contact_tel,'')) LIKE '%"
							+ searchValue + "%' ");
		}
//		querys.add(" u.id = " + userId + " ");
		
		// TODO 待报价状态
		querys.add(" fp.status = 2 ");
		querys.add(" (fpi.status = 0 or fpi.status = 1) ");
		querys.add(" qp.status is null ");
		querys.add(" fp.deleted = 0 ");
		querys.add(" fpi.deleted = 0 ");
		querys.add(" fpi.check_status = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = " fpi.herb_id,fpi.specifications,fp.publish_dt desc ";

		PageHelper.startPage(offset, limit);
		List<Map> mapList = purchaseService.getExtraPurchases(query,userId, orderByClause);
		if (CollectionUtils.isNotEmpty(mapList)) {
			return ConvertUtils.sourceToCamelCaseMap(mapList);
		}
		return Lists.newArrayList();
	}

	public Object myList(Integer userId, Byte type, Integer page, Integer limit, String sort, String order) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}

		List<String> querys = Lists.newArrayList();
//		querys.add(" fs.user_id = " + userId + " ");
		querys.add(" fs.deleted = 0 ");
//		querys.add(" uha.deleted = 0 ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		String orderByClause = null;
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
			orderByClause = " fs.id desc ";
		}

		PageHelper.startPage(page, limit);
		List<Map> mapList = purchaseService.getPurchases(query, orderByClause);
		Page<Map> list = (Page) mapList;

		Map<String, Object> data = Maps.newHashMap();
		data.put("list", ConvertUtils.sourceToCamelCaseMap(list));
		data.put("total", list.getTotal());
		data.put("page", list.getPageNum());
		data.put("limit", list.getPageSize());
		data.put("pages", list.getPages());
		return ResponseUtil.ok(data);
	}

	public Object detail(Integer userId, Integer id, Integer itemId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		Map<String, Object> data = Maps.newHashMap();
		List<String> querys = Lists.newArrayList();
		querys.add(" u.id = " + userId + " ");
		querys.add(" fp.id = " + id + " ");
		querys.add(" fpi.id = " + itemId + " ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		List<Map> mapList = purchaseService.getPurchases(query, null);
		if (CollectionUtils.isNotEmpty(mapList)) {
			data.put("purchase", MapUtil.toCamelCaseMap(mapList.get(0)));
		} else {
			return ResponseUtil.fail(COMMON_DETAIL_IS_NULL, "采购详情不存在或已被删除");
		}
		return ResponseUtil.ok(data);
	}

	public Object extraDetail(Integer userId, Integer id, Integer itemId) {
		if (userId == null) {
			return ResponseUtil.unlogin();
		}
		Map<String, Object> data = Maps.newHashMap();
		List<String> querys = Lists.newArrayList();
//		querys.add(" u.id = " + userId + " ");
		querys.add(" fp.id = " + id + " ");
		querys.add(" fpi.id = " + itemId + " ");
		String query = StringUtils.collectionToDelimitedString(querys, "and");
		List<Map> mapList = purchaseService.getExtraPurchases(query,userId, null);
		if (CollectionUtils.isNotEmpty(mapList)) {
			data.put("purchase", MapUtil.toCamelCaseMap(mapList.get(0)));
		} else {
			return ResponseUtil.fail(COMMON_DETAIL_IS_NULL, "采购详情不存在或已被删除");
		}
		return ResponseUtil.ok(data);
	}
}